// Copyright (C) 2024 Shpz<shaaapz@gmail.com>. All Rights Reserved.

/**
 * 弹簧臂调试组件。
 * 
 * 在编辑器/运行时阶段绘制弹簧臂调试视图。
 */

import { Component, CurveRange, Node, gfx, GradientRange, Label, Line, math, _decorator, find, Color } from 'cc';
import { EDITOR } from 'cc/env';
import { SpringArmComponent } from './SpringArmComponent';

const { ccclass, property, executeInEditMode, requireComponent, menu, disallowMultiple } = _decorator;

@ccclass('SpringArmDebugComponent')
@executeInEditMode
@requireComponent(Line)
@menu("SpringArm/SpringArmDebug")
@disallowMultiple
export class SpringArmDebugComponent extends Component {
    @property({
        type: SpringArmComponent,
        tooltip: "调试的弹簧臂组件"
    })
    protected springArm: SpringArmComponent;

    protected pointerTip: Node;

    start() {
        this.pointerStyle();
    }

    update(deltaTime: number) {
        this.refreshDebugView();
    }

    protected pointerStyle() {
        if (EDITOR) {
            return;
        }

        this.pointerTip = new Node("PointerTip");
        find("Canvas").addChild(this.pointerTip);
        this.pointerTip.setPosition(0, 200, 0);
        this.pointerTip.layer = 1 << 25;

        let label = this.pointerTip.addComponent(Label);
        label.string = "点下屏幕进入鼠标无限移动模式";
        label.color = Color.RED;
        label.fontSize = 40;

        const canvas = gfx.Device.canvas;
        canvas.addEventListener(
            "click",
            () => {
                this.pointerTip.active = false;

                canvas.requestPointerLock();
            }
        );
    }

    /**
     * 刷新调试视图
     */
    protected refreshDebugView() {
        if (this.springArm) {
            let line = this.getComponent(Line);
            line.worldSpace = true;
            line.width.mode = CurveRange.Mode.Constant;
            line.width.constant = 0.05;
            line.color.mode = GradientRange.Mode.Color;
            line.color.color = math.Color.RED;

            line.positions = [
                this.springArm.targetOffsetPosition,
                this.springArm.socketOffsetPosition
            ];
        }
    }
}